package com.tbit.uqbike.service.rpcservice.impl;

import com.alibaba.fastjson.JSONObject;
import com.tbit.uqbike.enums.SystemCodeEnum;
import com.tbit.uqbike.manager.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;

/**
 * @author MyWin E-mail:335918956@qq.com
 * @version 1.0
 * @createTime 2019-12-09 10:43
 */
@Service("cwsSmsService")
@Slf4j
public class CwsSmsServiceImpl extends BaseSmsService {
    /**
     * 接入密钥
     */
    private static final String secret = "tbit36987";

    public CwsSmsServiceImpl() {

    }

    @Override
    public Map<String, Object> sendSms(String country, String phone, String content, Map<String, Object> exParam) {
        HttpClient client = new HttpClient();
        PostMethod post = null;

        try {
            post = new PostMethod("http://www.cheweishi.cn/smsAction!gpsSendSms.do");
            post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
            NameValuePair phonePair = new NameValuePair("phone", phone);
            NameValuePair contentPair = new NameValuePair("content", content);
            NameValuePair secretPair = new NameValuePair("secret", secret);
            post.setRequestBody(new NameValuePair[]{phonePair, contentPair, secretPair});
            client.executeMethod(post);
            String result = post.getResponseBodyAsString();
            boolean res = JSONObject.parseObject(result).getBoolean("res");
            if (res) {
                return null;
            }
            log.error(String.format("CWS 短信通道发送短信失败,%s,%s,%s", phone, content, result));
            throw new BaseException(SystemCodeEnum.SEND_SMS_CODE_FAIL);
        } catch (IOException e) {
            log.error(String.format("CWS 短信通道发送短信失败,%s,%s,%s", phone, content, e.getMessage()));
            throw new BaseException(SystemCodeEnum.SEND_SMS_CODE_FAIL);
        } finally {
            post.releaseConnection();
        }
    }

}
